//
//  UNSwipeView.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/8/8.
//


import UIKit
import SwiftUI
import SwipeActions
import Combine


//lazy var swipe: UNSwipeView = {
//    let swipe = UNSwipeView(contentView: vview, actionModels: [.init(title: "one",backgroundColor: .red),.init(title: "two",backgroundColor: .green)] )
//    return swipe
//}()

// 通过转接器添加
//let hostingController = UIHostingController(rootView: sepiw )
//addChild(hostingController)
//hostingController.view.translatesAutoresizingMaskIntoConstraints = false
//view.addSubview(hostingController.view)
//
//// 设置布局约束
//NSLayoutConstraint.activate([
//    hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
//    hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
//    hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
//    hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
//])
//
//hostingController.didMove(toParent: self)

// 代码打开按钮
//swipe.open.send()




// 通用的UIViewController，用于承载传入的view
open class HostingViewController: UIViewController {
    private var customView: UIView
    
    public init(view: UIView) {
        self.customView = view
        super.init(nibName: nil, bundle: nil)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func loadView() {
        self.view = customView
    }
}

// 通用包装器
@available(iOS 13.0, *)
public struct ViewWrapper: UIViewControllerRepresentable {
    let view: UIView
    
    public func makeUIViewController(context: Context) -> HostingViewController {
        HostingViewController(view: view)
    }
    
    public func updateUIViewController(_ uiViewController: HostingViewController, context: Context) {
        // 如果需要动态更新，可以在这里实现
    }
}





@available(iOS 14.0, *)
public struct SwipeActionModel: Hashable{
    
    public enum actionType {
        case title
        case image
    }
    
    var id: Int = 0
    
    var type: actionType = .title
    
    var title: String = ""
    
    var titleColor: UIColor = UIColor.black
    
    var backgroundColor: UIColor = UIColor(Color.primary.opacity(0.1))
    
    public init(type: actionType, title: String,titleColor: UIColor = .black , backgroundColor: UIColor) {
        self.type = type
        self.title = title
        self.titleColor = titleColor
        self.backgroundColor = backgroundColor
    }
    
}

@available(iOS 14.0, *)
public struct UNSwipeView: View {
    
    public static let hiddenSwipeNotification = Notification.Name(rawValue: "hiddenSwipe")
    
    public static func notificationHiddenSwipe(location: CGPoint? = nil){
        NotificationCenter.default.post( name: UNSwipeView.hiddenSwipeNotification ,object: self,userInfo: ["location":location])
    }
    
    public init(contentView: UIView, actionModels: [SwipeActionModel],style: SwipeActionStyle? = nil,cornerRadius: CGFloat? = nil,delete: Bool = false, open: PassthroughSubject<Void, Never> = PassthroughSubject<Void, Never>()) {
        self.contentView = contentView
        self.actionModels = actionModels
        self.open = open
    }
    
    let contentView: UIView
    let actionModels:[SwipeActionModel]
    @State public  var open = PassthroughSubject<Void, Never>()
    @State public  var close = PassthroughSubject<Void, Never>()
    
    let actionBlock: (_ id: Int)->Void = {_ in }
    
    public var body: some View {
        SwipeView {
            ViewWrapper(view: contentView)
        } trailingActions: { context in
            ForEach(actionModels, id: \.self) { mod in
                if mod.type == .title {
                    SwipeAction( LocalizedStringKey(mod.title),backgroundColor: Color(mod.backgroundColor) ) {
                        actionBlock(mod.id)
                    }.onReceive(open) { _ in
                        NotificationCenter.default.post( name: UNSwipeView.hiddenSwipeNotification ,object: self,userInfo: nil)
                        context.state.wrappedValue = .expanded
                    }.onReceive(close) { _ in
                        context.state.wrappedValue = .closed
                    }.foregroundColor( Color(mod.titleColor) )
                }else{
                    SwipeAction(systemImage: mod.title) {
                        actionBlock(mod.id)
                    }.onReceive(open) { _ in
                        NotificationCenter.default.post( name: UNSwipeView.hiddenSwipeNotification ,object: self,userInfo: nil)
                        context.state.wrappedValue = .expanded
                    }.onReceive(close) { _ in
                        context.state.wrappedValue = .closed
                    }.foregroundColor( Color(mod.titleColor) )
                }
            }
        }
        .swipeActionsStyle(.mask)
        .swipeActionCornerRadius(0)
        .swipeSpacing(0)
        .swipeActionsMaskCornerRadius(0)
        .onReceive(NotificationCenter.default.publisher(for: UNSwipeView.hiddenSwipeNotification )) { notification in
            // 键盘即将隐藏时的处理
            close.send()
        }
        
    }
}

@available(iOS 14.0, *)
public struct UNSwipeDeleteView: View {
    
    public init(contentView: UIView) {
        self.contentView = contentView
        
    }
    
    let identifier = UUID()
    
    let contentView: UIView
    public var deleteActionBlock: ()->Void = {}
    var index: Int = 0
    
    @State public var open = PassthroughSubject<Void, Never>()
    @State public var close = PassthroughSubject<Void, Never>()
    @State public var notification = PassthroughSubject<Void, Never>()
    
    public var body: some View {
        SwipeView {
            ViewWrapper(view: contentView)
        } trailingActions: { context in
            
            notification.send()
            
            return SwipeAction("删除", backgroundColor: .red) {
                deleteActionBlock()
            }
            .allowSwipeToTrigger()
            .onReceive(open) { _ in
                context.state.wrappedValue = .expanded
            }.onReceive(close) { _ in
                context.state.wrappedValue = .closed
            }
            .foregroundColor( .white )
            
        }
        .swipeActionsStyle(.mask)
        .swipeActionCornerRadius(0)
        .swipeSpacing(0)
        .swipeActionsMaskCornerRadius(0)
        .transition(.swipeDelete)
        .onReceive(NotificationCenter.default.publisher(for: UNSwipeView.hiddenSwipeNotification )) { notification in
            // 键盘即将隐藏时的处理
            guard let receivedIdentifier = notification.userInfo?["id"] as? UUID else {
               close.send()
               return
           }
           
           if receivedIdentifier != self.identifier {
               close.send()
           }
        }.onReceive(notification) { _ in
            NotificationCenter.default.post(name: UNSwipeView.hiddenSwipeNotification, object: self, userInfo: ["id": identifier])
        }
    }
    
    
    
}





// MARK: - View Extension for Conditional Modifiers
private extension View {
    @ViewBuilder
    func conditionalModifier<Content: View>(
        _ condition: Bool,
        @ViewBuilder transform: (Self) -> Content
    ) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
    
    // 可选：单独处理可选值的扩展
    @ViewBuilder
    func applyIfNotNil<T>(_ value: T?, transform: (Self, T) -> some View) -> some View {
        if let value = value {
            transform(self, value)
        } else {
            self
        }
    }
}
